﻿
// AriesDoc.cpp : CAriesDoc 类的实现
//

#include "stdafx.h"
// SHARED_HANDLERS 可以在实现预览、缩略图和搜索筛选器句柄的
// ATL 项目中进行定义，并允许与该项目共享文档代码。
#ifndef SHARED_HANDLERS
#include "Aries.h"
#endif

#include "AriesDoc.h"
#include "LeftView.h"

#include <propkey.h>

//#include <afxtempl.h>

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

// CAriesDoc

IMPLEMENT_DYNCREATE(CAriesDoc, CDocument)

BEGIN_MESSAGE_MAP(CAriesDoc, CDocument)
END_MESSAGE_MAP()


// CAriesDoc 构造/析构

CAriesDoc::CAriesDoc()
//	: m_Code(_T(""))
{
	// TODO: 在此添加一次性构造代码

}

CAriesDoc::~CAriesDoc()
{
}

BOOL CAriesDoc::OnNewDocument()
{
	if (!CDocument::OnNewDocument())
		return FALSE;

	// TODO: 在此添加重新初始化代码
	// (SDI 文档将重用该文档)
	this->pLeftView->CreateFinanceStatement();

	return TRUE;
}




// CAriesDoc 序列化

void CAriesDoc::Serialize(CArchive& ar)
{
	if (ar.IsStoring())
	{
		// TODO: 在此添加存储代码
	}
	else
	{
		// TODO: 在此添加加载代码
	}
}

#ifdef SHARED_HANDLERS

// 缩略图的支持
void CAriesDoc::OnDrawThumbnail(CDC& dc, LPRECT lprcBounds)
{
	// 修改此代码以绘制文档数据
	dc.FillSolidRect(lprcBounds, RGB(255, 255, 255));

	CString strText = _T("TODO: implement thumbnail drawing here");
	LOGFONT lf;

	CFont* pDefaultGUIFont = CFont::FromHandle((HFONT) GetStockObject(DEFAULT_GUI_FONT));
	pDefaultGUIFont->GetLogFont(&lf);
	lf.lfHeight = 36;

	CFont fontDraw;
	fontDraw.CreateFontIndirect(&lf);

	CFont* pOldFont = dc.SelectObject(&fontDraw);
	dc.DrawText(strText, lprcBounds, DT_CENTER | DT_WORDBREAK);
	dc.SelectObject(pOldFont);
}

// 搜索处理程序的支持
void CAriesDoc::InitializeSearchContent()
{
	CString strSearchContent;
	// 从文档数据设置搜索内容。
	// 内容部分应由“;”分隔

	// 例如:  strSearchContent = _T("point;rectangle;circle;ole object;")；
	SetSearchContent(strSearchContent);
}

void CAriesDoc::SetSearchContent(const CString& value)
{
	if (value.IsEmpty())
	{
		RemoveChunk(PKEY_Search_Contents.fmtid, PKEY_Search_Contents.pid);
	}
	else
	{
		CMFCFilterChunkValueImpl *pChunk = NULL;
		ATLTRY(pChunk = new CMFCFilterChunkValueImpl);
		if (pChunk != NULL)
		{
			pChunk->SetTextValue(PKEY_Search_Contents, value, CHUNK_TEXT);
			SetChunkValue(pChunk);
		}
	}
}

#endif // SHARED_HANDLERS

// CAriesDoc 诊断

#ifdef _DEBUG
void CAriesDoc::AssertValid() const
{
	CDocument::AssertValid();
}

void CAriesDoc::Dump(CDumpContext& dc) const
{
	CDocument::Dump(dc);
}
#endif //_DEBUG


// CAriesDoc 命令


void CAriesDoc::GetDbData(void)
{
	
    
	//根据输入条件决定标题显示
    int nYear=_ttoi(m_Year);
	int nNyear=_ttoi(m_Nyear);
	int i=1;
	CString strYear;
	CString sqlstr;
	PGresult *res;
   	char * sqlcmd;
	int count=0;
	int iLen,iSize;
	CString sTbname;
	vector<vector <CString> > *ptr;
	
	for (int type=1;type<=3;type++)
	{
		switch(type)
		{
			case 1:
				sTbname=_T("stock.general.balancesheet");
				ptr=&m_BalanceSheet;
				break;
			case 2:
				sTbname=_T("stock.general.profitstatement");
				ptr=&m_Profit;
				break;
			case 3:
				sTbname=_T("stock.general.cashflow");
				ptr=&m_CashFlow;
				break;
		}

		//test
	

		sqlstr.Format(_T("select * from %s WHERE \"SecuritiesCode\"='%s\' AND extract(month from \"DeclareDate\")=12 AND extract(year from \"DeclareDate\")<=%s ORDER BY \"DeclareDate\" DESC limit %s;"),sTbname,m_Code,m_Year,m_Nyear);
		iLen=sqlstr.GetLength();
		iSize = WideCharToMultiByte(CP_ACP, 0, sqlstr, -1, NULL, 0, NULL, NULL);
		sqlcmd = (char*)malloc((iSize+1));
		WideCharToMultiByte(CP_ACP, 0, sqlstr, -1, sqlcmd, iSize, NULL, NULL);	

		res = PQexec(theApp.m_pConn, sqlcmd);
	

		if (PQresultStatus(res) != PGRES_TUPLES_OK)    
			{
				AfxMessageBox(_T("SQL命令执行不成功！！！"));
				PQclear(res);
			}
		else 
			{   
				int row=PQntuples(res);
				int column=PQnfields(res);
				//ptr->resize(row);  //方式一
				(*ptr).resize(row);  //方式二

				//m_BalanceSheet.resize(row);
				for (int i=0;i<row;i++)
				{
					//m_BalanceSheet[i].resize(column);
					(*ptr)[i].resize(column);
					for(int j=0;j<column;j++)
					{
						//m_BalanceSheet[i][j]=PQgetvalue(res, i,j);;
						//char *value=PQgetvalue(res, i,j);
						CString cs(PQgetvalue(res, i,j));
						(*ptr)[i][j]=cs;
						//TRACE(_T("%s\t"),(*ptr)[i][j]);
					}
					//TRACE("\n");
				}
		
				//CArray的写法，未成功，error C2248
				/*DATA temp;			
				temp.SetSize(row);           
				if( temp.IsEmpty() )
					AfxMessageBox(L"The list is currently empty.");
				for(int i=0;i<row;i++)
				{	
					for(int j=0;j<column;j++)
					{
						char *str=PQgetvalue(res, i,j);
						temp[i].SetAt(j,str);
					}
				}
				m_BalanceSheet.Copy(temp);
				TRACE("%d",m_BalanceSheet[0].GetSize());
				TRACE("\n%s\t%s",m_BalanceSheet[0][0],temp[0][0]);*/
				PQclear(res);
			}
		free(sqlcmd);	
	}
}


// 自由现金流计算
void CAriesDoc::FA_fcf(void)
{
	

	//方法一，利用现金流量表进行计算
	int row=(int)m_BalanceSheet.size();
	int nYear=_ttoi(m_Year);
	for (int i=0;i<row;i++,nYear--)
	{    
		 m_Fcf.push_back(fcf_t());   //Push back new subject created with default constructor.
		 m_Fcf[i].Year=nYear;
		 m_Fcf[i].AssetsDepreciationReserves = _ttof(m_CashFlow[i][62]);
		 m_Fcf[i].Depreciation = _ttof(m_CashFlow[i][63]);
		 m_Fcf[i].IntangibleAssetAmortization = _ttof(m_CashFlow[i][64]);
		 m_Fcf[i].DeferredExpenseAmortiztion = _ttof(m_CashFlow[i][65]);
		 m_Fcf[i].DeferredExpenseDecreased =  _ttof(m_CashFlow[i][66]);		
	     m_Fcf[i].AccruedExpenseAdded =  _ttof(m_CashFlow[i][67]);	
		 m_Fcf[i].FixedAssetScrapLoss = _ttof(m_CashFlow[i][69]);
		 m_Fcf[i].InventoryDecrease = _ttof(m_CashFlow[i][77]);
		 m_Fcf[i].OperateReceivableDecrease = _ttof(m_CashFlow[i][78]);
		 m_Fcf[i].OperatePayableIncrease = _ttof(m_CashFlow[i][79]);
		 m_Fcf[i].CapitalPaid = _ttof(m_CashFlow[i][35]);
		 //计算过程
		 m_Fcf[i].Noplat = _ttof(m_Profit[i][35])+_ttof(m_Profit[i][25])-_ttof(m_Profit[i][40]); //NOPLAT=EBIT(1-T)=营业利润+财务费用-所得税费用
		 m_Fcf[i].DeltaOperateCost = -m_Fcf[i].InventoryDecrease-m_Fcf[i].OperateReceivableDecrease-m_Fcf[i].DeferredExpenseDecreased-m_Fcf[i].OperatePayableIncrease- m_Fcf[i].AccruedExpenseAdded;	//营运资本增加＝存货增加＋经营性应收项目增加＋待摊费用增加－经营性应付增加－预提费用增加
		 m_Fcf[i].FCFvalue = m_Fcf[i].Noplat+ m_Fcf[i].AssetsDepreciationReserves+ m_Fcf[i].Depreciation+m_Fcf[i].IntangibleAssetAmortization+m_Fcf[i].DeferredExpenseAmortiztion+ m_Fcf[i].FixedAssetScrapLoss-m_Fcf[i].DeltaOperateCost- m_Fcf[i].CapitalPaid; //自由现金流=NOPLAT+折旧和摊销-营运资本增加-资本支出,其中NOPLAT=EBIT(1-T)
	     TRACE("%d\t%.2f\t%.2f\n",m_Fcf[i].Year,m_Fcf[i].Noplat,m_Fcf[i].FCFvalue);
	}
}
